package com.huatech.common.freemarker.tag;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huatech.common.annotation.EnumField;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 数据字典格式化自定义标签 在freemarker配置XML中定义为：
 * 
 * <pre>
 *        <property name="freemarkerVariables">
			<map>
				<entry key="fieldFormatter" value-ref="enumFieldFormatterDirective" /> 
			</map>
		  </property>
 * </pre>
 * 
 * 在页面使用例子：
 * 
 * <pre>
 *    <script type="text/javascript"> 
 *         <@fieldFormatter field="status" bean="com.huatech.domain.SystemConfig"/>
 *         ........     
 *           
 *          //easyui columns formatter值为自定义标签中的fieldName+"Formatter"
 *          {name:'status',label:'状态',sortable:false,formatter:statusFormatter}  
 *           
 *  	</script>
 * </pre>
 * 
 * @author lh
 * @version 2.0
 * @since 2017-05-22
 * 
 */
public class EnumFieldFormatterDirective implements TemplateDirectiveModel {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(EnumFieldFormatterDirective.class);

	private String fieldName;
	

	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		String beanName = params.get("bean").toString();
		fieldName = params.get("field").toString();
		if (StringUtils.isBlank(fieldName) || StringUtils.isBlank(beanName)) {
			return;
		}
		// 查询字段指定分类所有条目
		Class<?> clazz;
		try {
			clazz = Class.forName(beanName);
			Field fd = clazz.getDeclaredField(fieldName);
			EnumField enumField = fd.getAnnotation(EnumField.class);
			if (enumField != null) {
				Writer out = env.getOut();
				StringBuilder buffer = new StringBuilder();
				buffer.append(getJsonData( enumField.json()));
				buffer.append(createFormatterFunction());
				out.write(buffer.toString());				
			}
		}catch (NoSuchFieldException | SecurityException e1) {
			LOGGER.error(e1.getMessage(), e1);
		} catch (ClassNotFoundException e1) {
			LOGGER.error(e1.getMessage(), e1);
		}

	}

	private String getJsonData(String json) {
		StringBuilder buffer = new StringBuilder(128);
		String objectName = fieldName + "Data_";
		buffer.append("var " + objectName + " ={ \n");
		String[] array = json.substring(1, json.length() - 1).split(",");
		for (String string : array) {
			String[] kv = string.split("\\:");
			buffer.append("\t\"").append(kv[0].trim()).append("\" : \"").append(kv[1].trim()).append("\",\n");
		}
		buffer.deleteCharAt(buffer.length() - 2);
		buffer.append("\n  } ; \n");
		return buffer.toString();
	}

	private String createFormatterFunction() {
		StringBuilder buffer = new StringBuilder(50);
		String objectName = fieldName + "Data_";
		buffer.append("function ").append(fieldName).append("Formatter(cellvalue,options,rowData){\n");
		// 默认值为空字符串
		buffer.append("\t if(cellvalue == null){\n");
		buffer.append("\t\t return \"&nbsp;\"\n");
		buffer.append("\t }\n");
		buffer.append("\t var label= ").append(objectName).append("[cellvalue];\n");
		buffer.append("\t if(!label) { \n");
		buffer.append("\t\t return cellvalue ; \n");
		buffer.append("\t }  \n");
		buffer.append("\t return label;\n ");
		buffer.append("}\n");
		return buffer.toString();
	}
}
